package com.ylr.base.framework.interceptor;

import com.ylr.base.common.constant.Constant;
import com.ylr.base.common.po.user.UserPo;
import com.ylr.base.common.utils.UserUtils;
import com.alibaba.fastjson2.JSON;
import com.ylr.base.common.utils.HttpUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2023-04-26 21:25:01
 * className: FeignInterceptor
 * version: 1.0
 * description:
 */
@Slf4j
@Component
public class FeignInterceptor implements RequestInterceptor {

    /**
     * 项目简称
     */
    @Value("${spring.application.simple-name:ylr}")
    private String applicationSimpleName;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 获取请求request对象
        HttpServletRequest request = HttpUtils.getHttpServletRequest();

        // 获取请求用户对象
        UserPo userPo = UserUtils.getUser();
        log.info("==> {}", userPo);
        log.info("applicationSimpleName={}", applicationSimpleName);

        requestTemplate.header(Constant.SOURCE, applicationSimpleName);
        requestTemplate.header(Constant.CHANNEL, request.getHeader(Constant.CHANNEL));
        requestTemplate.header(Constant.AUTH_RESULT, Constant.AUTH_PASS);
        String requestIp = (String) request.getAttribute(Constant.REQUEST_IP);
        if (StringUtils.isBlank(requestIp)) {
            log.debug("从请求头中获取请求ip地址");
            requestIp = request.getHeader(Constant.REQUEST_IP);
        }
        requestTemplate.header(Constant.REQUEST_IP, requestIp);
        if (Objects.nonNull(userPo)) {
            requestTemplate.header(UserPo.class.getSimpleName(), JSON.toJSONString(userPo));
        }

    }
}
